package com.better.common.jwtauth.secruity;

import com.better.common.utils.Encodes;
import com.better.common.utils.EncryptUtils;
import com.better.common.utils.serc.Digests;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * 自定义加密器
 * Created by Administrator on 2017/11/13.
 */
public class MyPasswordEncode extends EncryptUtils implements PasswordEncoder {

    /***
     * 加密
     * ***/
    @Override
    public String encode(CharSequence rawPassword) {
        String plain = Encodes.unescapeHtml(rawPassword.toString());
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    }

    /***
     * 密码验证
     * @param rawPassword  明文
     * @param encodedPassword  密文（编译密码及加密）
     * **/
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        String plain = Encodes.unescapeHtml(rawPassword.toString());
        byte[] salt = Encodes.decodeHex(encodedPassword.substring(0, 16));
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        return encodedPassword.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
    }

    public static void main(String[] args) {
        MyPasswordEncode encoder=new MyPasswordEncode();
        String pass= encoder.encode("zxy111111");
        System.out.println(pass);
       System.out.println(encoder.matches("123456","64dd860fb823c29ec96ddaac68003d82d9a644475d3c43518f38b7d8"));

    }
}
